<template>
    <div class="w-full">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="120px" class="w-full">
            <!-- 顶部 -->
            <div class="flex p-6 pt-0 items-center">
                <div class="relative">
                    <!-- 上传头像 -->
                    <el-upload ref="avatarUploadRef" :show-file-list="false" accept=".jpg,.png,.webp,.jpeg,"
                        :auto-upload="false" :on-change="handleAvartarChange" :http-request="uploadAvatar">
                        <img v-if="avatarFileList.length != 0" :src="avatarFileList[0].url"
                            class="object-cover h-28 w-28 rounded-lg">
                        <div v-else class="h-28 w-28 rounded-lg bg-gray-100 flex justify-center items-center">
                            <el-icon color="#999" :size="40">
                                <Plus />
                            </el-icon>
                        </div>
                    </el-upload>
                </div>
                <div class="flex flex-col ml-10 justify-between">
                    <div>
                        <!-- 上传语音包标题 -->
                        <el-form-item label="语音包名称" prop="voicePackageName">
                            <el-input v-model="formData.voicePackageName" placeholder="请输入语音包名称" class="mb-3" />
                        </el-form-item>
                        <!-- 上传语音包简介 -->
                        <el-form-item label="语音包简介" prop="voicePackageIntro">
                            <el-input v-model="formData.voicePackageIntro" type="textarea" :rows="3"
                                placeholder="请输入语音包简介" />
                        </el-form-item>
                    </div>
                </div>
            </div>

            <div class="px-6 relative">
                <!-- Tab 和添加按钮 -->
                <div class="flex">
                    <el-tabs class="myElTabs flex-1" v-model="activeName">
                        <el-tab-pane :label="`语音条`" name="first">
                            <!-- 自定义音频文件列表 -->
                            <ul class="mt-5">
                                <li class="flex border-b py-2 my-5 items-center" v-for="(item, index) in voiceList"
                                    :key="index">
                                    <!-- 文件名编辑 -->
                                    <el-input v-model="item.name" class="flex-1 mr-3" placeholder="输入文件名" size="small"
                                        clearable />
                                    <div class="flex items-center ml-3">
                                        <!-- 删除按钮 -->
                                        <el-button type="danger" size="small" @click="deleteVoice(index)">删除</el-button>
                                    </div>
                                </li>
                            </ul>
                        </el-tab-pane>
                    </el-tabs>
                    <!-- 添加按钮 -->
                    <div class="flex">
                        <el-button type="success" @click="confirmCreate">
                            确定上传
                        </el-button>
                        <el-upload class="ml-2" ref="audioUploadRef" :show-file-list="false"
                            accept=".mp3,.wma,.aac,.ogg,.wav" :multiple="true" :on-remove="removeAudioList"
                            :auto-upload="false" :http-request="uploadAudio" :on-change="handleAudioChange">
                            <el-button type="primary">
                                上传音频
                            </el-button>
                        </el-upload>
                        <el-button class="ml-2" type="info" @click="showRecordDialog = true">
                            录音
                        </el-button>
                    </div>
                </div>

                <!-- 录音弹窗 -->
                <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false"
                    v-model="showRecordDialog" @close="handleDialogClose">
                    <AudioRecorder @recordingEnded="hanhleRecordingEnded" />
                </el-dialog>
            </div>
        </el-form>
    </div>
</template>

<script setup lang="ts">
    import AudioRecorder from "@renderer/components/AudioRecorder.vue";
    import { ref, getCurrentInstance } from 'vue'
    import { Plus } from '@element-plus/icons-vue'
    import type { UploadFile } from 'element-plus'
    import { uploadFile } from "@renderer/api/upload";
    import { voicePackageCreateApi } from "@renderer/api/voice";

    const { proxy } = getCurrentInstance();

    const showRecordDialog = ref < Boolean > (false)
    const activeName = ref < string > ('first')

    const avatarFileList = ref([]) // 头像的文件列表

    const formData = ref({
        voicePackageName: '',
        voicePackageIntro: '',
    })

    const formRules = ref({
        voicePackageName: [
            { required: true, message: '请输入语音包名称', trigger: 'blur' }
        ],
        voicePackageIntro: [
            { required: true, message: '请输入语音包简介', trigger: 'blur' }
        ]
    });

    const voiceList = ref < { name: string; url: string }[] > ([]); // 语音文件列表
    const selectAudioList = ref([])

    const avatarUploadRef = ref(null);
    const audioUploadRef = ref(null);

    /**
     * 上传后的url
     * **/
    const avartarUrl = ref("");
    const audioUrlList = ref([])


    const confirmCreate = async () => {
        // 触发表单验证
        const isValid = await proxy?.$refs.form.validate()
        if (!isValid) {
            return ElMessage({
                type: 'info',
                message: '信息不全，无法创建，请检查！！',
            });
        }
        await uploadAvatar()
        await uploadAudio()
        await voicePackageCreateApi({
            "name": formData.value.voicePackageName,
            "intro": formData.value.voicePackageIntro,
            "avatar": avartarUrl.value,
            "voiceList": audioUrlList.value
        })
    }

    const uploadAvatar = async () => {
        if (!avatarFileList.value[0] || avatarFileList.value.length === 0) {
            console.warn("没有要上传的头像");
            return;
        }
        const result = await uploadFile(avatarFileList.value[0].raw);
        avartarUrl.value = result
        console.log("所有头像文件", avartarUrl.value);
    }

    const uploadAudio = async () => {
        if (!selectAudioList.value || selectAudioList.value.length === 0) {
            console.warn("没有要上传的文件");
            return;
        }
        if (selectAudioList.value.length < 3) {
            return ElMessage({
                type: 'info',
                message: '请上传至少三条音频',
            });
        }
        for (const file of selectAudioList.value) {
            try {
                const audioIndex = selectAudioList.value.findIndex((item) => item.uid === file.uid);
                const result = await uploadFile(file.raw);
                audioUrlList.value.push({
                    "voiceUrl": result,
                    "name": voiceList.value[audioIndex].name
                });
            } catch (error) {
                console.error("文件上传失败：", file.name, error);
            }
        }
        console.log("所有音频文件", audioUrlList.value);
    };

    const hanhleRecordingEnded = (blob) => {
        showRecordDialog.value = false; // 关闭弹窗
    };

    //删除音频
    const deleteVoice = (index) => {
        // 检查 index 是否有效
        if (index < 0 || index >= voiceList.value.length) {
            console.warn(`无效的索引：${index}`);
            return;
        }
        // 获取 voiceList 中的目标元素
        const target = voiceList.value[index];
        const targetUid = target.uid; // 获取目标元素的 uid
        // 删除 voiceList 中的元素
        voiceList.value.splice(index, 1);
        // 在 selectAudioList 中找到 uid 对应的元素并删除
        const audioIndex = selectAudioList.value.findIndex((item) => item.uid === targetUid);
        if (audioIndex !== -1) {
            selectAudioList.value.splice(audioIndex, 1); // 删除 selectAudioList 中的目标元素
        }
    };

    const handleAudioChange = proxy?.$utils.debounce((file, fileList_) => {
        console.log("jdias1", fileList_);
        selectAudioList.value = fileList_;
        for (let index = 0; index < fileList_.length; index++) {
            const element = fileList_[index];
            voiceList.value.push({
                uid: element.uid,
                name: element.name.split('.').slice(0, -1).join('.'),
                url: ""
            })
        }
    }, 500);

    const handleAvartarChange = (file: UploadFile) => {
        //如果上传的图片没有url字段，手动生成
        if (!file.url) file.url = URL.createObjectURL(file.raw as any)
        avatarFileList.value[0] = file
    }
</script>

<style scoped>
    :deep(.el-tabs__item) {
        color: var(--playBg);
    }

    :deep(.el-tabs__active-bar) {
        background-color: var(--active);
    }

    :deep(.el-textarea__inner:focus) {
        --el-input-focus-border-color: var(--playBg);
    }

    :deep(.el-input__wrapper) {
        --el-input-focus-border-color: var(--playBg);
    }
</style>